<!--

    XTemp1.0 to XSLT2.0 Translator:
    
    Notice:
    The material contained herein is not a license, either expressly or impliedly, to any 
    intellectual property owned or controlled by any of the authors or developers of this 
    material. The material contained herein is provided on an "AS IS" basis and to 
    the maximum extent permitted by applicable law, this material is provided AS IS AND WITH 
    ALL FAULTS, and the authors and developers of this material hereby disclaim all 
    other warranties and conditions, either express, implied or statutory, including, but not 
    limited to, any (if any) implied warranties, duties or conditions of  merchantability, 
    of fitness for a particular purpose, of accuracy or completeness of responses, of results, 
    of workmanlike effort, of lack of viruses, and of lack of negligence. ALSO, THERE IS NO 
    WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, QUIET POSSESSION, CORRESPONDENCE TO 
    DESCRIPTION OR NON-INFRINGEMENT WITH REGARD TO THIS MATERIAL.
    
    IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THIS MATERIAL BE LIABLE TO ANY OTHER 
    PARTY FOR THE COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS OF USE, 
    LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, INDIRECT, OR SPECIAL DAMAGES 
    WHETHER UNDER CONTRACT, TORT, WARRANTY, OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR 
    ANY OTHER AGREEMENT RELATING TO THIS MATERIAL, WHETHER OR NOT SUCH PARTY HAD ADVANCE 
    NOTICE OF THE POSSIBILITY OF SUCH DAMAGES.
    

    Content Desccription: XTemp1.0 to XSLT2.0 Translator, addressing only the "core" subset 
    of the XTemp script language.

    Role: generates the stylesheet that has semantically equivalent execution as
    the XTemp script provided as source.
    
    @authors:
    Chuck Morris (Northrop-Grumman) - initial authoring.
    Jacques Durand (Fujitsu America, Inc.) - modifications.

    @version 1.0, 11/April/2011

    Use of this code is subject to the Mozilla Public License 1.1 
    (MPL 1.1) http://opensource.org/licenses/mozilla1.1.php

  -->

<xsl:transform
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
   xmlns:txsl="http://www.w3.org/1999/XSL/Transform/target"
   xmlns:xtemp="http://docs.oasis-open.org/tamie/xtemp/200909"
   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
   xmlns:fn="http://www.w3.org/2005/xpath-functions"
   xmlns:translator="translator"
   version="2.0">

  <xsl:output method="xml" indent="yes"/>

  <xsl:strip-space elements="*"/>
  <xsl:output indent="yes"/>
  <xsl:namespace-alias stylesheet-prefix="txsl" result-prefix="xsl"/>

  <xsl:param name="main"/>

    <xsl:template name="error">
    <xsl:param name="message"/>
    <xsl:message terminate="yes">
      <!--
	  <xsl:text>Error</xsl:text>
	  <xsl:if test="function-available('saxon:line-number')" xmlns:saxon="http://saxon.sf.net/">
            <xsl:text> on line </xsl:text>
            <xsl:value-of select="saxon:line-number(.)"/>
	  </xsl:if>
	  -->
      <xsl:text>: </xsl:text>
      <xsl:value-of select="$message"/>
    </xsl:message>
  </xsl:template>

  <xsl:template name="type-attribute">
    <xsl:if test="@type and @type != 'xml'">
      <xsl:attribute name="as">
        <xsl:text>xsd:</xsl:text>
        <xsl:value-of select="@type"/>
      </xsl:attribute>
    </xsl:if>
  </xsl:template>

  <xsl:template name="get-cursor-name">
    <xsl:param name="last-name"/>
    <xsl:param name="increment" select="xsd:integer(0)"/>
    <xsl:choose>
      <xsl:when test="self::xtemp:scriplet">
        <xsl:value-of select="concat('translator:cursor', $last-name)"/>
        <xsl:if test="$last-name=''">-0</xsl:if>
      </xsl:when>
      <xsl:otherwise>
        <xsl:variable name="num" select="count(preceding-sibling::*[descendant-or-self::xtemp:catch|descendant-or-self::xtemp:start[not(@vptsync = false)]]) + $increment"/>
        <xsl:for-each select="..">
          <xsl:call-template name="get-cursor-name">
            <xsl:with-param name="last-name">
              <xsl:if test="$num gt 0">
                <xsl:value-of select="concat('-', $num)"/>
              </xsl:if>
              <xsl:value-of select="$last-name"/>
            </xsl:with-param>
          </xsl:call-template>
        </xsl:for-each>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="xtemp:script-package">
    <xsl:apply-templates select="*"/>
  </xsl:template>

  <xsl:template match="xtemp:execution-context">
    <xsl:apply-templates select="*"/>
  </xsl:template>

  <xsl:template match="xtemp:nms-binding"/>

  <xsl:template match="xtemp:start-with"/>

  <xsl:template match="xtemp:event-board"/>

  <xsl:template match="xtemp:scriplet">
    <txsl:template name="{@name}">
      <txsl:param name="translator:cursor-0"/>
      <xsl:apply-templates select="xtemp:param"/>
      <txsl:copy-of select="$translator:cursor-0"/>
      <xsl:call-template name="process-block">
        <xsl:with-param name="elements" select="*[not(self::xtemp:param)]"/>
      </xsl:call-template>
    </txsl:template>
  </xsl:template>

  <xsl:template name="process-block">
    <xsl:param name="elements"/>

    <xsl:for-each select="$elements">
      <xsl:choose>
        <xsl:when test="preceding-sibling::xtemp:exit"/>
        <xsl:when test="descendant-or-self::xtemp:exit|descendant-or-self::xtemp:catch|descendant-or-self::xtemp:start[not(@vptsync = false)]">
          <xsl:variable name="varname" select="concat('var_', generate-id())"/>
          <xsl:choose>
            <xsl:when test="self::xtemp:var">
              <txsl:variable name="{$varname}">
		<xsl:call-template name="process-block">
		  <xsl:with-param name="elements" select="node()"/>
		</xsl:call-template>

              </txsl:variable>
              <txsl:variable name="{@name}">
                <txsl:call-template name="translator:remove-translator-tags">
                  <txsl:with-param name="tags" select="${$varname}"/>
                </txsl:call-template>
              </txsl:variable>
              <xsl:if test="descendant-or-self::xtemp:catch|descendant-or-self::xtemp:start[not(@vptsync = false)]">
                <txsl:copy-of select="(${$varname}//translator:cursor)[position()=last()]"/>
              </xsl:if>

              <xsl:if test="descendant-or-self::xtemp:exit and not(self::xtemp:var)">
                <txsl:copy-of select="${$varname}//translator:exitreport"/>
              </xsl:if>

            </xsl:when>
            <xsl:otherwise>
              <txsl:variable name="{$varname}">
                <xsl:apply-templates select="."/>
              </txsl:variable>
              <txsl:copy-of select="${$varname}"/>
            </xsl:otherwise>
          </xsl:choose>
          <xsl:if test="descendant-or-self::xtemp:catch|descendant-or-self::xtemp:start[not(@vptsync = false)]">
            <xsl:if test="following-sibling::* or parent::xtemp:loop">
              <txsl:variable>
                <xsl:attribute name="name">
                  <xsl:call-template name="get-cursor-name">
                    <xsl:with-param name="increment" select="xsd:integer(1)"/>
                  </xsl:call-template>
                </xsl:attribute>
                <txsl:copy-of select="(${$varname}//translator:cursor)[position()=last()]"/>
              </txsl:variable>
            </xsl:if>
          </xsl:if>

          <xsl:if test="descendant-or-self::xtemp:exit and not(self::xtemp:var)">
            <txsl:if test="not(${$varname}//translator:exitreport)" translator:mode="begin"/>
          </xsl:if>

        </xsl:when>
        <xsl:otherwise>
          <xsl:apply-templates select="."/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:for-each>

    <xsl:for-each select="$elements[not(self::xtemp:var)][.//xtemp:exit]">
      <txsl:if translator:mode="end"/>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match="xtemp:start">
    <xsl:if test="parent::xtemp:function">
      <xsl:call-template name="error">
        <xsl:with-param name="message">start is not allowed inside of a function.</xsl:with-param>
      </xsl:call-template>
    </xsl:if>
    <xsl:variable name="cursor-varname">
      <xsl:call-template name="get-cursor-name"/>
    </xsl:variable>

    <txsl:variable name="{fn:concat($cursor-varname, '_vpt_', @scriplet) }">
      <xsl:choose>
	<xsl:when test="@vptset and @vptset ne ''">
	  <!-- translator:cursor last-id="{fn:concat('{', '$translator:cursor-0/translator:cursor/@last-id','}')}" time="{fn:concat('{', @vptset,'}')}"/ -->
	  <translator:cursor last-id="{fn:concat('{', '$translator:cursor-0/translator:cursor/@last-id','}')}" 
			     time="{@vptset}"/>
	</xsl:when>
	<xsl:otherwise>
	  <xsl:attribute name="select">
	    <xsl:value-of select="fn:concat('$', $cursor-varname)"/>
	  </xsl:attribute>
	</xsl:otherwise>
      </xsl:choose>
    </txsl:variable>

    <txsl:call-template name="{@scriplet}">
      <txsl:with-param name="translator:cursor-0" select="${fn:concat($cursor-varname, '_vpt_', @scriplet) }"/>
      <xsl:apply-templates select="xtemp:with-param"/>
    </txsl:call-template>
    <xsl:if test="@vptsync = false">
      <txsl:copy-of select="${$cursor-varname}"/>
    </xsl:if>
  </xsl:template>

  <xsl:template match="xtemp:with-param">
    <txsl:with-param name="{@name}">
      <xsl:choose>
        <xsl:when test="@expr">
          <xsl:attribute name="select">
            <xsl:value-of select="@expr"/>
          </xsl:attribute>
          <xsl:if test="* or (normalize-space(.) != '')">
            <xsl:call-template name="error">
              <xsl:with-param name="message"><xsl:value-of select="name()"/> may not have both an expr attribute and enclosed content.</xsl:with-param>
            </xsl:call-template>
          </xsl:if>
        </xsl:when>
        <xsl:otherwise>
          <xsl:apply-templates select="*|text()"/>
        </xsl:otherwise>
      </xsl:choose>
    </txsl:with-param>
  </xsl:template>

  <xsl:template match="xtemp:param">
    <txsl:param name="{@name}">
      <xsl:call-template name="type-attribute"/>
      <xsl:choose>
        <xsl:when test="@expr">
          <xsl:attribute name="select">
            <xsl:value-of select="@expr"/>
          </xsl:attribute>
          <xsl:if test="* or (normalize-space(.) != '')">
            <xsl:call-template name="error">
              <xsl:with-param name="message"><xsl:value-of select="name()"/> may not have both an expr attribute and enclosed content.</xsl:with-param>
            </xsl:call-template>
          </xsl:if>
        </xsl:when>
        <xsl:otherwise>
          <xsl:apply-templates select="*|text()"/>
        </xsl:otherwise>
      </xsl:choose>
    </txsl:param>
  </xsl:template>

  <xsl:template match="xtemp:message">
    <txsl:message>
      <xsl:apply-templates select="*|text()"/>
    </txsl:message>
  </xsl:template>

  <xsl:template match="xtemp:exit">
    <xsl:if test="@message">
      <txsl:message>
        <xsl:value-of select="@message"/>
      </txsl:message>
    </xsl:if>
    <translator:exitreport>
      <xsl:apply-templates select="node()"/>
    </translator:exitreport>
  </xsl:template>

  <xsl:template match="xtemp:decide">
    <txsl:choose>
      <xsl:apply-templates select="*"/>
    </txsl:choose>
  </xsl:template>

  <xsl:template match="xtemp:if|xtemp:else-if">
    <xsl:choose>
      <xsl:when test="parent::xtemp:decide">
        <txsl:when test="{@expr}">
          <xsl:call-template name="process-block">
            <xsl:with-param name="elements" select="node()"/>
          </xsl:call-template>
        </txsl:when>
      </xsl:when>
      <xsl:otherwise>
        <txsl:if test="{@expr}">
          <xsl:call-template name="process-block">
            <xsl:with-param name="elements" select="node()"/>
          </xsl:call-template>
        </txsl:if>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="xtemp:else">
    <txsl:otherwise>
      <xsl:call-template name="process-block">
        <xsl:with-param name="elements" select="node()"/>
      </xsl:call-template>
    </txsl:otherwise>
  </xsl:template>

  <xsl:template match="xtemp:function">
    <txsl:function name="{@name}">
      <xsl:apply-templates select="node()"/>
    </txsl:function>
  </xsl:template>

 <xsl:template match="xtemp:post">
  </xsl:template>

  <xsl:template match="xtemp:call-adapter">
  </xsl:template>


  <xsl:template match="xtemp:catch">
    <xsl:variable name="cursor-varname">
      <xsl:call-template name="get-cursor-name"/>
    </xsl:variable>
    
    <txsl:variable name="cursor-last-id" select="${$cursor-varname}/translator:cursor/@last-id"/>
    <txsl:variable name="cursor-time"    select="${$cursor-varname}/translator:cursor/@time"/>
    
    <xsl:variable name="compound-condition">
      <xsl:text>fn:concat( '(</xsl:text>
      <!-- CHANGE vptend -->
      <xsl:if test="@vptend">
	<xsl:text>xsd:dateTime(</xsl:text>
	<xsl:value-of select="if (//xtemp:event-board/xtemp:eventbind ) then //xtemp:event-board/xtemp:eventbind/@timestampexpr else '@timestamp'" />
	<xsl:text>) lt  xsd:dateTime(</xsl:text>
	<xsl:value-of select="if (fn:starts-with(@vptend, '{')) then 
			      fn:substring-after(fn:substring-before(@vptend,'}'), '{' )
			      else concat('&quot;', @vptend,'&quot;' )"/>
	<xsl:text>)) and (</xsl:text>
      </xsl:if>

      <xsl:value-of select="xtemp:match/xtemp:condition"/>
      <!-- CHANGE gen -->
      <xsl:text>) and xsd:integer(</xsl:text>
      <xsl:variable name="vselect0">
	<xsl:choose>
	  <xsl:when test="//xtemp:event-board/xtemp:eventbind[@id]">
	    <xsl:value-of select="//xtemp:event-board/xtemp:eventbind/@id"/>
	  </xsl:when>
	  <xsl:when test="//xtemp:event-board/xtemp:eventbind[not(@id)]">
	    <xsl:value-of select="'fn:count(preceding-sibling::node()) + 1'"/>
	  </xsl:when>
	  <xsl:otherwise>
	    <xsl:value-of select="'@id'"/>
	  </xsl:otherwise>
	</xsl:choose>
      </xsl:variable>

      <xsl:value-of select="$vselect0"/>

      <!-- xsl:value-of select="if (//xtemp:event-board/xtemp:eventbind ) then 
	   //xtemp:event-board/xtemp:eventbind/@id 
	   else '@id'" / -->
      <xsl:text>) gt xsd:integer(', $cursor-last-id , fn:concat( ') and xsd:dateTime(</xsl:text>
      <xsl:value-of select="if (//xtemp:event-board/xtemp:eventbind ) then 
			    //xtemp:event-board/xtemp:eventbind/@timestampexpr 
			    else '@timestamp'" />
      <xsl:text>) ge xsd:dateTime("', $cursor-time,</xsl:text>
      <xsl:if test="not(@tryfor)">
          <!-- complete the dateTime() and concat() calls-->
          <xsl:text> '")' ) )</xsl:text>
      </xsl:if>
      <xsl:if test="@tryfor">
	<!-- CHANGE gen -->
        <!-- xsl:text> and xsd:dateTime(@timestamp) le xsd:dateTime($</xsl:text -->
        <xsl:text>fn:concat( '") and xsd:dateTime(</xsl:text>
	<xsl:value-of select="if (//xtemp:event-board/xtemp:eventbind ) then //xtemp:event-board/xtemp:eventbind/@timestampexpr else '@timestamp'" />
	<xsl:text>) le xsd:dateTime("', $cursor-time, '") + xsd:dayTimeDuration(</xsl:text>
	<xsl:value-of select="if (fn:starts-with(@tryfor, '{')) then 
			      fn:substring-after(fn:substring-before(@tryfor,'}'), '{' )
			      else concat('&quot;', @tryfor,'&quot;' )"/>
        <xsl:text>) ' ) ) )</xsl:text>
      </xsl:if>
      
    </xsl:variable>

    <!-- CHANGE gen -->
    <!-- txsl:for-each select="(/xtemp:event-board/xtemp:events/xtemp:event[{$compound-condition}])[1]" -->
    <txsl:variable name="event-board-name">
        <xsl:value-of select="@eboard"/>
    </txsl:variable>
    
    <txsl:variable name="catch-timeout">
      <xsl:choose>
        <xsl:when test="@tryfor">
	  <xsl:value-of select="@tryfor"/>
	</xsl:when>
	<xsl:otherwise>
          P365D
        </xsl:otherwise>
      </xsl:choose>
    </txsl:variable>
    

    <xsl:variable name="vselect-1">
      <xsl:choose>
	<xsl:when test="//xtemp:event-board/xtemp:eventbind">
	  <xsl:value-of select="fn:concat('(', //xtemp:event-board/@root, '/', //xtemp:event-board/xtemp:eventbind, '[', $compound-condition, '])[1]')"/>
	</xsl:when>
	<xsl:otherwise>
          <xsl:value-of select="fn:concat( 'xtemp:query-board( $event-board-name,',
                                           $compound-condition,
                                           ', ''//xtemp:event[ compound-condition ]'', false(), $catch-timeout ) ' )"/>
	</xsl:otherwise>
      </xsl:choose>
    </xsl:variable>
    <txsl:for-each select="{$vselect-1}">

      <txsl:copy-of select="."/>
      <translator:cursor>
        <txsl:attribute name="time">

	  <!-- CHANGE gen -->
          <!-- txsl:value-of select="@timestamp"/ -->

	  <xsl:variable name="vselect-2">
	    <xsl:choose>
	      <xsl:when test="//xtemp:event-board/xtemp:eventbind">
		<xsl:value-of select="//xtemp:event-board/xtemp:eventbind/@timestampexpr"/>
	      </xsl:when>
	      <xsl:otherwise>
                <xsl:value-of select="'self::node()/xtemp:event/@timestamp'"/>
	      </xsl:otherwise>
	    </xsl:choose>
	  </xsl:variable>
          
          <txsl:value-of select="{$vselect-2}"/>
	  <!--
              <txsl:choose>
		<txsl:when test="xsd:dateTime(@timestamp) gt xsd:dateTime(${$cursor-varname}/translator:cursor/@time)">
		  <txsl:value-of select="@timestamp"/>
		</txsl:when>
		<txsl:otherwise>
		  <txsl:value-of select="${$cursor-varname}/translator:cursor/@time"/>
		</txsl:otherwise>
              </txsl:choose>
	      -->
        </txsl:attribute>
        <txsl:attribute name="last-id">

	  <!-- CHANGE gen -->
          <!-- txsl:value-of select="@id"/ -->
	  <xsl:variable name="vselect-3">
	    <xsl:choose>
	      <xsl:when test="//xtemp:event-board/xtemp:eventbind[@id]">
		<xsl:value-of select="//xtemp:event-board/xtemp:eventbind/@id"/>
	      </xsl:when>
	      <xsl:when test="//xtemp:event-board/xtemp:eventbind[not(@id)]">
		<xsl:value-of select="'fn:count(preceding-sibling::node()) + 1'"/>
	      </xsl:when>
	      <xsl:otherwise>
		<xsl:value-of select="'self::node()/xtemp:event/@id'"/>
	      </xsl:otherwise>
	    </xsl:choose>
	  </xsl:variable>
          <txsl:value-of select="{$vselect-3}"/>

        </txsl:attribute>
      </translator:cursor>
    </txsl:for-each>
    
    <!-- CHANGE gen -->
    <!-- txsl:if test="not(/xtemp:event-board/xtemp:events/xtemp:event[{$compound-condition}])" -->
    <xsl:variable name="vselect-4">
      <xsl:choose>
	<xsl:when test="//xtemp:event-board/xtemp:eventbind">
	  <xsl:value-of select="fn:concat('not(', //xtemp:event-board/@root, '/', //xtemp:event-board/xtemp:eventbind, '[', $compound-condition, '])')"/>
	</xsl:when>
	<xsl:otherwise>
            <xsl:value-of select="fn:concat( 'not( xtemp:query-board( $event-board-name,',
                                             $compound-condition,
                                             ', ''//xtemp:event[ compound-condition ]'', false(), ''PT0.100S'' ) )' )"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <txsl:if test="{$vselect-4}">

      <translator:cursor>
        <txsl:attribute name="time">
          <xsl:choose>
            <xsl:when test="@tryfor">
              <txsl:value-of select="xsd:dateTime(${$cursor-varname}/translator:cursor/@time) + 
				     xsd:dayTimeDuration({if (fn:starts-with(@tryfor, '{')) then 
			      fn:substring-after(fn:substring-before(@tryfor,'}'), '{' )
			      else @tryfor})"/>
            </xsl:when>
            <xsl:otherwise>
              <txsl:value-of select="${$cursor-varname}/translator:cursor/@time"/>
            </xsl:otherwise>
          </xsl:choose>
        </txsl:attribute>
        <txsl:attribute name="last-id">
          <txsl:value-of select="${$cursor-varname}/translator:cursor/@last-id"/>
        </txsl:attribute>
      </translator:cursor>
    </txsl:if>
  </xsl:template>

  <xsl:template match="xtemp:eval">
    <txsl:copy-of select="{@expr}"/>
  </xsl:template>

  <xsl:template match="xtemp:var|xtemp:lvar">
    <xsl:if test="self::xtemp:lvar">
      <xsl:if test="not(parent::xtemp:on-start)">
        <xsl:call-template name="error">
          <xsl:with-param name="message">lvar must be an immediate child of on-start.</xsl:with-param>
        </xsl:call-template>
      </xsl:if>
    </xsl:if>
    <txsl:variable name="{@name}">
      <xsl:call-template name="type-attribute"/>
      <xsl:choose>
        <xsl:when test="@expr">
          <xsl:attribute name="select">
            <xsl:value-of select="@expr"/>
          </xsl:attribute>
          <xsl:if test="* or (normalize-space(.) != '')">
            <xsl:call-template name="error">
              <xsl:with-param name="message"><xsl:value-of select="name()"/> may not have both an expr attribute and enclosed content.</xsl:with-param>
            </xsl:call-template>
          </xsl:if>
        </xsl:when>
        <xsl:otherwise>

	  <xsl:choose>
	    <xsl:when test="text()">
              <xsl:apply-templates select="text()"/>
	    </xsl:when>
	    <xsl:otherwise>
	      <xsl:call-template name="process-block">
		<xsl:with-param name="elements" select="*[not(self::xtemp:param)]"/>
	      </xsl:call-template>
	    </xsl:otherwise>
	  </xsl:choose>

        </xsl:otherwise>
      </xsl:choose>
    </txsl:variable>
  </xsl:template>

  <xsl:template match="xtemp:until">
    <xsl:if test="not(parent::xtemp:loop)">
      <xsl:call-template name="error">
        <xsl:with-param name="message">until must be an immediate child of loop.</xsl:with-param>
      </xsl:call-template>
    </xsl:if>
    <txsl:choose translator:mode="begin"/>
    <txsl:when test="not({@expr})" translator:mode="begin"/>
  </xsl:template>

  <xsl:template match="xtemp:on-start">
    <xsl:if test="not(parent::xtemp:loop)">
      <xsl:call-template name="error">
        <xsl:with-param name="message">on-start must be an immediate child of loop.</xsl:with-param>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

  <xsl:template match="xtemp:on-final">
    <xsl:if test="not(parent::xtemp:loop)">
      <xsl:call-template name="error">
        <xsl:with-param name="message">on-final must be an immediate child of loop.</xsl:with-param>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

  <xsl:template match="xtemp:lvar-next">
    <xsl:if test="not(parent::xtemp:loop)">
      <xsl:call-template name="error">
        <xsl:with-param name="message">lvar-next must be an immediate child of loop.</xsl:with-param>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

  <xsl:template match="xtemp:loop">
    <xsl:variable name="cursor-varname">
      <xsl:call-template name="get-cursor-name"/>
    </xsl:variable>

    <!-- Process on-start -->
    <xsl:apply-templates select="xtemp:on-start/*"/>

    <!-- Capture context parameters -->
    <xsl:variable name="context-params">
      <xsl:for-each select="ancestor::*">
        <xsl:for-each select="preceding-sibling::*|.">
          <xsl:for-each select="self::xtemp:var|self::xtemp:param|self::xtemp:loop/xtemp:on-start/xtemp:lvar">
            <txsl:param name="{@name}">
              <xsl:call-template name="type-attribute"/>
            </txsl:param>
          </xsl:for-each>
        </xsl:for-each>
      </xsl:for-each>
      <xsl:for-each select="preceding-sibling::*">
        <xsl:for-each select="self::xtemp:var|self::xtemp:param|self::xtemp:loop/xtemp:on-start/xtemp:lvar">
          <txsl:param name="{@name}">
            <xsl:call-template name="type-attribute"/>
          </txsl:param>
        </xsl:for-each>
      </xsl:for-each>
    </xsl:variable>

    <!-- Call template for body -->
    <txsl:call-template name="loop_{generate-id(.)}">
      <txsl:with-param name="{$cursor-varname}" select="${$cursor-varname}"/>
      <xsl:for-each select="$context-params/*">
        <txsl:with-param name="{@name}" select="${@name}"/>
      </xsl:for-each>
      <xsl:for-each select="xtemp:on-start/xtemp:lvar">
        <txsl:with-param name="{@name}" select="${@name}"/>
      </xsl:for-each>
    </txsl:call-template>

    <!-- Generate template for body -->
    <txsl:template name="loop_{generate-id(.)}">
      <txsl:param name="{$cursor-varname}"/>
      <xsl:copy-of select="$context-params"/>
      <xsl:for-each select="xtemp:on-start/xtemp:lvar">
        <txsl:param name="{@name}">
          <xsl:call-template name="type-attribute"/>
        </txsl:param>
      </xsl:for-each>
      <xsl:variable name="block">
        <xsl:call-template name="process-block">
          <xsl:with-param name="elements" select="node()"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:choose>
        <xsl:when test="$block//translator:exitreport">
          <xsl:variable name="count" select="count($block/node())"/>
          <xsl:copy-of select="$block/node()[position() &lt; $count]"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:copy-of select="$block"/>
        </xsl:otherwise>
      </xsl:choose>
      <txsl:call-template name="loop_{generate-id(.)}">
        <txsl:with-param name="{$cursor-varname}">
          <xsl:attribute name="select">
            <xsl:text>$</xsl:text>
            <xsl:for-each select="*[position()=last()]">
              <xsl:call-template name="get-cursor-name">
                <xsl:with-param name="increment">
                  <xsl:choose>
                    <xsl:when test="self::xtemp:catch|self::xtemp:start[not(@vptsync = false)]">1</xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                  </xsl:choose>
                </xsl:with-param>
              </xsl:call-template>
            </xsl:for-each>
          </xsl:attribute>
        </txsl:with-param>
        <xsl:for-each select="$context-params/*">
          <txsl:with-param name="{@name}" select="${@name}"/>
        </xsl:for-each>
        <xsl:for-each select="xtemp:on-start/xtemp:lvar">
          <txsl:with-param name="{@name}">
            <xsl:attribute name="select">
              <xsl:choose>
                <xsl:when test="../../xtemp:lvar-next[@name=current()/@name]">
                  <xsl:value-of select="../../xtemp:lvar-next[@name=current()/@name]/@expr"/>
                </xsl:when>
                <xsl:otherwise>$<xsl:value-of select="@name"/></xsl:otherwise>
              </xsl:choose>
            </xsl:attribute>
          </txsl:with-param>
        </xsl:for-each>
      </txsl:call-template>
      <xsl:if test="$block//translator:exitreport">
        <txsl:if translator:mode="end"/>
      </xsl:if>
      <xsl:for-each select="xtemp:until">
        <txsl:when translator:mode="end"/>
        <txsl:otherwise>
          <xsl:apply-templates select="../xtemp:on-final/*"/>
        </txsl:otherwise>
        <txsl:choose translator:mode="end"/>
      </xsl:for-each>
    </txsl:template>
  </xsl:template>

  <xsl:template match="text()">
    <xsl:copy/>
  </xsl:template>
  
  <xsl:template match="*">
    <xsl:copy>
      <xsl:copy-of select="@*"/>
      <xsl:call-template name="process-block">
        <xsl:with-param name="elements" select="node()"/>
      </xsl:call-template>
    </xsl:copy>
  </xsl:template>

  <xsl:template name="get-path">
    <xsl:variable name="elements">
      <xsl:for-each select="preceding-sibling::*[@translator:mode]|self::*[@translator:mode='end']">
        <xsl:variable name="level" select="count(preceding-sibling::*[@translator:mode='begin']) + count(self::*[@translator:mode='begin']) - count(preceding-sibling::*[@translator:mode='end']) - count(self::*[@translator:mode='end'])"/>
        <x name="{name()}" mode="{@translator:mode}">
          <xsl:attribute name="level">
            <xsl:choose>
              <xsl:when test="@translator:mode='begin'">
                <xsl:value-of select="$level - 1"/>
              </xsl:when>
              <xsl:otherwise>
                <xsl:value-of select="$level"/>
              </xsl:otherwise>
            </xsl:choose>
          </xsl:attribute>
        </x>
      </xsl:for-each>
    </xsl:variable>
    <xsl:for-each select="$elements/*">
      <xsl:variable name="name" select="@name"/>
      <xsl:variable name="level" select="@level"/>
      <xsl:if test="@mode='begin' and @name=$name and not(following-sibling::*[@mode='end' and @level=$level])">
        <xsl:text>/</xsl:text>
        <xsl:value-of select="$name"/>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>

  <xsl:template name="serialize-content">
    <!-- Serialize the content of an instruction.  Nested templates are skipped.
         Elements between an element with @translator:mode='begin' and the matching
         element with @translator:mode='end' are promoted a level.  -->
    <xsl:param name="serialize-path"/>

    <xsl:for-each select="*|text()">
      <xsl:choose>
        <xsl:when test="self::text()">
          <xsl:copy/>
        </xsl:when>
        <xsl:when test="not(self::xsl:template or @translator:mode='end')">
          <xsl:variable name="path">
            <xsl:call-template name="get-path"/>
          </xsl:variable>
          <xsl:choose>
            <xsl:when test="$path != $serialize-path"/>
            <xsl:when test="@translator:mode='begin'">
              <xsl:variable name="new-path" select="concat($path, '/', name())"/>
              <xsl:copy>
                <xsl:for-each select="@*">
                  <xsl:if test="name() != 'translator:mode'">
                    <xsl:copy/>
                  </xsl:if>
                </xsl:for-each>
                <xsl:for-each select="..">
                  <xsl:call-template name="serialize-content">
                    <xsl:with-param name="serialize-path" select="$new-path"/>
                  </xsl:call-template>
                </xsl:for-each>
              </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
              <xsl:copy>
                <xsl:copy-of select="@*"/>
                <xsl:call-template name="serialize-content"/>
              </xsl:copy>
            </xsl:otherwise>
          </xsl:choose>
        </xsl:when>
      </xsl:choose>
    </xsl:for-each>
  </xsl:template>

  <xsl:template match="/">
    <xsl:variable name="main">
      <xsl:choose>
        <xsl:when test="xtemp:script-package/xtemp:execution-context/xtemp:start-with">
          <xsl:value-of select="xtemp:script-package/xtemp:execution-context/xtemp:start-with/@scriplet"/>
        </xsl:when>
        <xsl:when test="$main != ''">
          <xsl:value-of select="$main"/>
        </xsl:when>
        <xsl:when test="//xtemp:scriplet[@name='main']">main</xsl:when>
        <xsl:otherwise>
          <xsl:message terminate="yes">You must supply a &quot;main&quot; parameter to indicate the starting scriplet name.</xsl:message>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:variable>

    <txsl:transform version="2.0">
      <xsl:copy-of select="*/namespace::*"/>
      <xsl:namespace name="xsd">http://www.w3.org/2001/XMLSchema</xsl:namespace>

      <txsl:output omit-xml-declaration="yes" indent="yes"/>

      <!-- Phase 1: Process instructions.  Produces nested templates and elements with
           translator:mode='begin' and translator:mode='end' attributes. -->
      <xsl:variable name="results">
        <xsl:apply-templates select="*"/>
      </xsl:variable>
      <!--
	  <xsl:message>Phase 1 results:</xsl:message>
	  <xsl:copy-of select="$results"/>
	  -->

      <xsl:for-each select="$results">
        <xsl:call-template name="serialize-content"/>
      </xsl:for-each>

      <txsl:template match="/">
        <txsl:call-template name="translator:remove-translator-tags">
          <txsl:with-param name="tags">
            <txsl:call-template name="{$main}">
              <txsl:with-param name="translator:cursor-0">
                <translator:cursor last-id="0">
                  <txsl:attribute name="time">
		    <!-- CHANGE gen -->
                    <!-- txsl:value-of select="/xtemp:event-board/xtemp:events/xtemp:event[1]/@timestamp"/ -->
		    <xsl:variable name="vselect-5">
		      <xsl:choose>
			<xsl:when test="//xtemp:event-board/xtemp:eventbind">
			  <xsl:value-of select="fn:concat(//xtemp:event-board/@root, '/', //xtemp:event-board/xtemp:eventbind, '[1]/', //xtemp:event-board/xtemp:eventbind/@timestampexpr)"/>
			</xsl:when>
			<xsl:otherwise>
                          <xsl:value-of select="fn:concat(  'xtemp:query-board( '''', '''' ',
                                                            ', ''//xtemp:event[1]/@timestamp'', false(), ''P365D'' )' )"/>
			</xsl:otherwise>
		      </xsl:choose>
		    </xsl:variable>
                    
                    <!-- $vselect-5 will contain the first event which matches the query //xtemp:event[1]/@timestamp.
                         For this reason, we will have to retrieve below only the timestamp attribute
                    -->                    
		    <txsl:value-of select="({$vselect-5})/xtemp:event/@timestamp"/>

                  </txsl:attribute>
                </translator:cursor>
              </txsl:with-param>
            </txsl:call-template>
          </txsl:with-param>
        </txsl:call-template>
      </txsl:template>
      
      <txsl:template name="translator:remove-translator-tags">
        <txsl:param name="tags"/>
        <txsl:for-each select="$tags">
          <txsl:choose>
            <txsl:when test="self::translator:cursor"/>
            <txsl:when test="self::translator:exitreport">
              <txsl:call-template name="translator:remove-translator-tags">
                <txsl:with-param name="tags" select="node()"/>
              </txsl:call-template>
            </txsl:when>
            <txsl:otherwise>
              <txsl:copy>
                <txsl:copy-of select="@*"/>
                <txsl:call-template name="translator:remove-translator-tags">
                  <txsl:with-param name="tags" select="node()"/>
                </txsl:call-template>
              </txsl:copy>
            </txsl:otherwise>
          </txsl:choose>
        </txsl:for-each>
      </txsl:template>

      <!-- Phase 2: Move each template to the root level.  Promote elements between
           "begin" and "end" elements a level deeper. -->
      <xsl:for-each select="$results//xsl:template">
        <xsl:copy>
          <xsl:copy-of select="@*"/>
          <xsl:call-template name="serialize-content"/>
        </xsl:copy>
      </xsl:for-each>

    </txsl:transform>
  </xsl:template>
</xsl:transform>
